package com.itheima.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Tensin
 * @version 1.0
 * @date
 * 复写service，按照最后字段分配调用方法
 */

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求路径
        String requestURI = req.getRequestURI();

        //从/处切割,获取对应的方法名
        int lastIndexOf = requestURI.lastIndexOf('/');
        String substring = requestURI.substring(lastIndexOf + 1);

        //反射调用方法。
        Class<? extends BaseServlet> usedClass = this.getClass(); //谁调用，this就是谁

        try {
            Method method = usedClass.getMethod(substring, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
